<!-- AI告警督办-列表页（首页） -->
<template>
  <view class="list-all">
    <Header :title="title" bgColor="#fff"/>
    <search-box ref="searchBOX" placeholder="请输入学校名称" mode="input" :searchContent="queryForm.schoolName" @search="search" @clear="searchClear" :showSift="true"  @shiftReset="shiftReset" @shiftConfirm="shiftConfirm" :iconFlag="iconFlag">
      <template #shift class="popup-content">

        <view v-if="areaLevel > 1" class="popup-title-row">
          <text>地区</text>
        </view>
        <view v-if="areaLevel > 1" class="popup-con-row">
          <view class="item-occupied" @click="openArea">
            {{ areaName ? areaName : '请选择地区' }}
          </view>
          <uv-picker ref="areaPicker" :columns="areaList" :loading="loading" :title="'地区'" keyName="name" @change="areaChange" @confirm="areaPickerConfirm"></uv-picker>
        </view>


        <view class="popup-title-row">
          <text>告警日期</text>
        </view>
        <view class="popup-date-row">
          <view class="date" style="width: 100%;" @click="openCalendars">{{ dateRange ? dateRange : '请选择告警日期' }}</view>
          <uv-calendars ref="calendars" allowSameDay="true" mode="range" @confirm="searchDate"></uv-calendars>
        </view>
        <view class="popup-title-row">
          <text>告警类型</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item, index) in stateTagist" :key="index" class="item"
                :class="{actived:item.value === stateTag}" @click="rectifyStateTagFun(item)">
            {{ item.label }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>整改状态</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item, index) in stateList" :key="index" class="item"
                :class="{actived:item.value === state}" @click="rectifyStateFun(item)">
            {{ item.label }}
          </view>
        </view>
        <view class="popup-title-row">
          <text>督办状态</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item, index) in alarmUrgeStateList" :key="index" class="item"
                :class="{actived:item.value === alarmUrgeState}" @click="alarmUrgeStateFun(item)">
            {{ item.label }}
          </view>
        </view>
      </template>
    </search-box>
    <scroll-view :scroll-y="true" class="canteen-scroll-height"
                 refresher-enabled="true" :refresher-triggered="triggered"
                 :lower-threshold="50" @scrolltolower="nextPage"
                 :refresher-threshold="80" refresher-background="rgb(244, 244, 244)"
                 @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                 @refresherrestore="onRestore" @refresherabort="onAbort"
                 refresher-default-style="none">
      <view v-if="emptyFlag" class="empty-box">
        <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"></uv-empty>
      </view>
      <view v-else class="option-box">
        <view v-for="(item, index) in dataList" :key="item.id">
          <card-list :rowId="item.id"
                     @handleCard="handleView(item)"
                     :imageApi="true"
                     :imagePath="imageUrl(item.image)"
                     :imageTag="warningStateTagFormatter(item.stateTag)"
                     :deltaState="getDeltaState(item.alarmUrgeState)"
                     :deltaStateColor="getDeltaStateClass(item.alarmUrgeState)"
                     :imageState="getImageState(item.state)"
                     :imageStateColor="getImageStateClass(item.state)"
                     :title="item.schoolName"
                     :labelList="['地区:', '告警日期:', '预警数量:']"
                     :valueList="[item.addressAll, dayjs(item.alarmDate).format('YYYY-MM-DD'), `${item.warnTotalNum}条`]"
                     :colorRendering="{row: [3], class: getColorClass(item.state)}"
                     :showCheckBox="false"
                     @onCheckboxChange="onCheckboxChange">
          </card-list>
        </view>
        <uni-load-more :status="loadingType" :content-text="contentText"/>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import api from "@/api/pco/alarm/alarmInfo.js";
import schoolApi from "@/api/school/school/school.js";
import areaApi from "@/api/system/area/area.js";
import cardList from "@/packagePcoCheck/components/card-list/index.vue";
import {ref} from "vue";
import {warningStateTagFormatter} from "@/utils/formValidate";
import dayjs from "dayjs";
import searchBox from "@/packagePcoCheck/components/search-box/index.vue";
import config from "@/common/config";
import {onLoad} from "@dcloudio/uni-app";
import homeAnalysis from "@/api/pco/homeAnalysis/homeAnalysis";
const {proxy} = getCurrentInstance();
let userInfo = ref(uni.getStorageSync('userInfo'));
let title = ref('告警档案');
let searchBOX = ref();
let schoolList = ref([]);
let stateList = ref([
  {label: '待整改', value: '0'},
  {label: '部分整改', value: '1'},
  {label: '整改完成', value: '2'},
]);
let stateTagist = ref([
  {label: '超期未整改', value: 'CQ'},
  {label: '预警复现', value: 'FX'},
]);
let alarmUrgeStateList = ref([
  {label: '已督办', value: '1'},
  {label: '未督办', value: '0'},
]);

let emptyFlag = ref(false);
let freshing = ref(false);
let triggered = ref(false);
let loadingType = ref('noMore');
let contentText = reactive({
  contentdown: "上拉显示更多",
  contentrefresh: "正在加载...",
  contentnomore: "没有更多数据了"
});
let dataList = reactive([]);
let queryForm = reactive({
  pageSize: 10,
  pageNum: 1,
  state: '',
  startDate: '',
  endDate: '',
  schoolName: '',
});
let total = ref(0);

/** 数据加载 */
onLoad((option) => {
  if (option.schoolId) {
    queryForm.schoolId = option.schoolId;
  }
});

/** 搜索数据列表 */
let search = (e) => {
  queryForm.schoolName= e
  queryForm.pageNum = 1;
  getListData();
}


let searchList = (e) => {
  queryForm.pageNum = 1;
  getListData();
}

/** 初始化 */
let getListData = () => {
  queryForm.userId = userInfo.value.user.id
  queryForm.params={schoolIds:schoolIds.value}
  proxy.http.post(api.alarmList, queryForm).then(res => {
    if (res.code === 0) {
      total.value = res.data.total;
      if (queryForm.pageNum === 1) {
        dataList.length = 0;
      }
      nextTick(()=>{
        dataList.push(...res.data.records);
        if (dataList.length < total.value) {
          loadingType.value = 'more';
        } else {
          loadingType.value = 'noMore';
        }
        emptyFlag.value = dataList.length <= 0;
      })
    }
  })
}

let imgMinioPath = ref(config.IMG_MINIO_PATH.replace("/schoolWeb",""));
let imageUrl = (imagePath) => {
  return imgMinioPath.value + imagePath;
}


let handleView = (item) => {
  uni.navigateTo({
    url: `/packagePcoCheck/pages/alarmInfo/baseInfo?id=${item.id}&urgeShow=1`
  });
}
let getSchoolList = () => {
  proxy.http.post(schoolApi.getOrgSchoolNoTenantId, {params:{sourceIds:schoolIds.value}}).then(res => {
    if (res.code === 0) {
      schoolList.value = res.data;
      schoolList.value.unshift({
        id: '',
        name: '全部'
      })
    }
  })
}

/** 搜索-日期 */
let dateChange = (e) => {
  queryForm.startDate = e;
  queryForm.endDate = e;
  searchList();
}
/** 滚动视图区域 */
/** 翻页 */
let nextPage = (e) => {
  if (queryForm.pageNum * queryForm.pageSize < total.value) {
    queryForm.pageNum++;
    getListData()
  }
}
/** 下拉 */
let onPulling = (e) => {
  freshing.value = false;
  setTimeout(() => {
    triggered.value = true;
  }, 1000)
}
/** 刷新 */
let onRefresh = (e) => {
  if (freshing.value) return;
  triggered.value = 'restore';
  setTimeout(() => {
    freshing.value = false;
    triggered.value = false;
  }, 1000)
  //获取数据的函数
  queryForm.pageNum = 1 // 记录数
  getListData()
}
let onRestore = (e) => {
  triggered.value = 'restore'; // 需要重置
}
let onAbort = (e) => {}
let popup = ref();
let loading = ref(false);

let schoolIds =  ref([]);
let getSchoolData= async (callback) => {
  let query = {
    dataScopeType: '1',
    sourceType: '02',
    orgDistrictId:userInfo.value.user.orgId,
  };
  let res = await proxy.http.asyncPost(homeAnalysis.getDataScopeInfoNoTenantId,query);
  if (res.code === 0) {
    let  ids = res.data.choose || [];
    if (ids.length > 0) {
      let res = await proxy.http.asyncPost(homeAnalysis.getOrgSchoolPage,{pageNum: -1,pageSize: -1,params:{ids:ids}});
      if (res.code === 0) {
        let orgSchoolData=res.data.records||[];
        if(userInfo.value.user.org.city){
          schoolIds.value = orgSchoolData.filter(item=>item.regulatoryUnitCode != "province").map(item => item.id);
        }else{
          schoolIds.value = orgSchoolData.map(item => item.id);
        }
        callback();
      }
    }
  }
};


onShow(() => {
  getSchoolData(() => {
    searchList();
    getSchoolList();
  });
  getAreaTree();
})

function getDeltaState (alarmUrgeState) {
  if (alarmUrgeState === '1') {
    return '已督';
  } else {
    return '未督';
  }
}

function getDeltaStateClass (alarmUrgeState) {
  if (alarmUrgeState === '1') {
    return 'blue';
  } else {
    return 'info';
  }
}

function getImageState (state) {
  if (state === '0') {
    return '待整改';
  } else if (state === '1') {
    return '部分整改';
  } else if (state === '2') {
    return '整改完成';
  }
}

function getImageStateClass (state) {
  if (state === '0') {
    return 'red';
  } else if (state === '1') {
    return 'yellow';
  } else if (state === '2') {
    return 'green';
  }
}

function getColorClass (state) {
  if (state === '0') {
    return 'red';
  } else if (state === '1') {
    return 'yellow';
  } else if (state === '2') {
    return 'green';
  }
}

// 弹出时间选择
let calendars = ref();
let openCalendars = (e) => {
  calendars.value.open();
}
// 搜索
let dateRange = ref();

let searchDate = (e) => {
  queryForm.startDate = e.range.before;
  queryForm.endDate = e.range.after;
  dateRange.value=queryForm.startDate+"~"+queryForm.endDate
}
// 清空
let searchClear = () => {
  queryForm.schoolName = '';
  searchList();
}

// 筛选 整改状态
const state = ref('');
const rectifyStateFun = (item) => {
  if (state.value === item.value) {
    state.value = '';
  } else {
    state.value = item.value;
  }
};

// 筛选 告警状态
const stateTag = ref('');
const rectifyStateTagFun = (item) => {
  if (stateTag.value === item.value) {
    stateTag.value = '';
  } else {
    stateTag.value = item.value;
  }
}
// 筛选 告警状态
const alarmUrgeState = ref('');
const alarmUrgeStateFun = (item) => {
  if (alarmUrgeState.value === item.value) {
    alarmUrgeState.value = '';
  } else {
    alarmUrgeState.value = item.value;
  }
}


// 筛选重置
let shiftReset = (e) => {
  state.value = '';
  stateTag.value = '';
  alarmUrgeState.value = '';
  queryForm.state = '';
  queryForm.stateTag = '';
  queryForm.startDate = '';
  queryForm.endDate = '';
  queryForm.alarmUrgeState = '';
  dateRange.value= '';
  queryForm.areaCode = '';
  areaCode.value = '';
  areaName.value = '';
  pickerValue.value = [0, 0, 0];
  defaultValue.value = [0, 0, 0];
  changeIcon();
  searchList();
}

// 筛选确认
let shiftConfirm = (e) => {
  queryForm.state = state.value;
  queryForm.stateTag = stateTag.value;
  queryForm.alarmUrgeState= alarmUrgeState.value;
  queryForm.areaCode = areaCode.value;
  changeIcon();
  searchList();
}

let iconFlag = ref(false);
let changeIcon = () => {
  iconFlag.value = !!(queryForm.startDate || queryForm.endDate || queryForm.state || queryForm.stateTag || queryForm.alarmUrgeState || queryForm.areaCode);
}


/** 筛选-地区 */
let areaList = ref([]); // 地区列表
let areaPicker = ref(''); // 地区选择器
let areaCode = ref(''); //地区编码
let areaName = ref(''); // 地区名称

let provinces = ref([]); // 省
let citys = ref([]); // 市
let areas = ref([]); // 区
let pickerValue = ref([0, 0, 0]); // 选择器值
let defaultValue = ref([0, 0, 0]); // 默认值
let areaTree = ref([]); // 地区树

let areaLevel = ref(3); //地区等级
let provinceDefault = ref({id: '0', name: '请选择', code: '',children: [{id: '0', name: '请选择', code: '', children: [{id: '0', name: '请选择', code: ''}]}]});
let cityDefault = ref({id: '', name: '请选择', code: '', children: [{id: '0', name: '请选择', code: ''}]});
let areaDefault = ref({id: '', name: '请选择', code: ''});

// 获取地区数据
let getAreaTree = (e) => {
  // 判断层级
  let province = userInfo.value.user.org.province;
  let city = userInfo.value.user.org.city;
  let county = userInfo.value.user.org.county;
  let areaId = county || city || province;
  areaLevel.value = county ? 1 : city ? 2 : 3;
  proxy.http.get(areaApi.getAreaTreaById, {areaId: areaId.toString().padEnd(12, '0') }).then((res) => {
    if (res.code === 0) {
      areaTree.value = [...res.data];
      areaTree.value.unshift(areaLevel.value === 3 ? provinceDefault.value : areaLevel.value === 2 ? cityDefault.value : areaDefault.value)
      if (areaTree.value && areaTree.value.length > 0) {
        for (let i = 1; i < areaTree.value.length; i++) {
          if (areaTree.value[i].children) {
            areaTree.value[i].children.unshift(areaLevel.value === 3 ? cityDefault.value : areaLevel.value === 2 ? areaDefault.value : '')
            for (let j = 1; j < areaTree.value[i].children.length; j++) {
              if (areaTree.value[i].children[j].children) {
                areaTree.value[i].children[j].children.unshift(areaDefault.value)
              }
            }
          }
        }
      }
      console.log(areaTree.value)
      provinces.value = areaTree.value.sort((left, right) => (Number(left.code) > Number(right.code) ? 1 : -1));
      handlePickValueDefault();
    } else {
      uni.showToast({title: res.msg, icon: 'none'});
    }
  })
}

/** 打开地区选择器 */
const openArea = () => {
  areaPicker.value.open();
  handlePickValueDefault();
};

/** 设置默认选择值 */
const handlePickValueDefault = () => {
  pickerValue.value[0] = getDefaultIndex(provinces.value, defaultValue.value[0]);
  if (areaLevel.value >= 2) {
    citys.value = provinces.value[pickerValue.value[0]]?.children || [];
    pickerValue.value[1] = getDefaultIndex(citys.value, defaultValue.value[1]);
  }
  if (areaLevel.value === 3) {
    areas.value = citys.value[pickerValue.value[1]]?.children || [];
    pickerValue.value[2] = getDefaultIndex(areas.value, defaultValue.value[2]);
  }
  setPickerIndexes();
};

/** 获取默认索引 */
const getDefaultIndex = (list, value) => {
  return value ? list.findIndex(item => Number(item.code) === value) : 0;
};

/** 设置选择器位置 */
const setPickerIndexes = () => {
  switch (areaLevel.value) {
    case 3:
      proxy.$refs.areaPicker.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]], true);
      areaList.value = [provinces.value, citys.value, areas.value];
      break;
    case 2:
      proxy.$refs.areaPicker.setIndexs([pickerValue.value[0], pickerValue.value[1]], true);
      areaList.value = [provinces.value, citys.value];
      break;
    case 1:
      proxy.$refs.areaPicker.setIndexs([pickerValue.value[0]], true);
      areaList.value = [provinces.value];
      break;
    default:
      break;
  }
};

/** 地区变化 */
const areaChange = ({ columnIndex, index, indexs }) => {
  if (areaLevel.value === 3) {
    if (columnIndex === 0) {
      citys.value = provinces.value[index]?.children || [];
      areas.value = citys.value[0]?.children || [];
      proxy.$refs.areaPicker.setIndexs([index, 0, 0], true);
    } else if (columnIndex === 1) {
      areas.value = citys.value[index]?.children || [];
      proxy.$refs.areaPicker.setIndexs([indexs[0], index, 0], true);
    }
    areaList.value = [provinces.value, citys.value, areas.value];
  } else if (areaLevel.value === 2) {
    if (columnIndex === 0) {
      citys.value = provinces.value[index]?.children || [];
      proxy.$refs.areaPicker.setIndexs([index, 0], true);
    }
    areaList.value = [provinces.value, citys.value];
  }
};

/** 确认选择地区 */
const areaPickerConfirm = (e) => {
  areaCode.value = '';
  areaName.value = '';
  pickerValue.value = e.indexs;
  if (e.value && e.value.length > 0) {
    for (let i = 0; i < e.value.length; i++) {
      defaultValue.value[i] = Number(e.value[i].code);
      areaCode.value = e.value[i].code || areaCode.value;
      areaName.value = e.value[i].name === '请选择' ? areaName.value : areaName.value + e.value[i].name;
    }
  }
};
</script>

<style scoped lang="scss">
@import '@/static/css/dailycheck/common.scss';

.list-all {
  margin: 0;
}

.bottom-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin: 24rpx auto;
}

.r-button {
  background-color: #3775F6 !important;
  border: 1px solid #3775F6;
  color: #fff !important;
  width: 30%;
}

.scroll-height {
  background: #f6f6f6;
  height: calc(100vh - 440rpx);
}

.canteen-scroll-height {
  background: #f6f6f6;
  height: calc(100vh - 440rpx);
}

::v-deep .uv-button--hairline {
  border-radius: 15rpx;
  height: 70rpx;
}

.areaWidth {
  position: relative;
  margin: 30rpx 0;
  width: 100%;

  ::v-deep .uv-textarea__field {
    text-align: left !important;
    padding: 10px !important;
  }
}

.popup-box {
  width: 100vw;
}

.popup-content {
  padding: 20rpx;
}

::v-deep .uv-tabs__wrapper {
  background: #f6f6f6;
}
.popup-con-row{
  margin-bottom: 30rpx;
}
</style>


